package cn.com.digitalnet.ad.web;

import java.util.Date;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.web.Servlets;

import com.google.common.collect.Maps;

import cn.com.digitalnet.ad.base.CrudController;
import cn.com.digitalnet.ad.base.CrudService;
import cn.com.digitalnet.ad.entity.SelfConstruction;
import cn.com.digitalnet.ad.service.SelfConstructionService;
import cn.com.digitalnet.ad.service.UserService;
import cn.com.digitalnet.ad.util.Holder;
import cn.com.digitalnet.ad.util.PropertiesHolder;


@Controller
@RequestMapping(value="selfConstruction")
public class SelfConstructionController extends CrudController<SelfConstruction> {
	
	private static final String PAGE_SIZE = "10";
	
	{
		sortTypes.put("id", "自动");
		sortTypes.put("pubdate", "自动");
	}
	
	@Autowired private  SelfConstructionService service;
	@Autowired UserService userService;
	@Autowired PropertiesHolder propertiesHolder;
	@Override
	protected CrudService<SelfConstruction> service() {
		return service;
	}

	@Override
	protected String english() {
		return "selfConstruction";
	}

	@Override
	protected String chinese() {
		return "";
	}

	@Override
	protected String parentMenu() {
		return  "selfConstruction";
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String list(@RequestParam(value="page", defaultValue="1")int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sortType", defaultValue = "id") String sortType,
			@RequestParam(value = "sortDire", defaultValue = "asc") String sortDire,
			Model model,
			ServletRequest request){
		model.addAttribute("types", SelfConstruction.types);
		model.addAttribute("statuss", SelfConstruction.statuss);
		model.addAttribute("users", userService.findToMap());
		
		//do
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		addSearchParam(searchParams);
		
		searchParams.put("order", "pubdate");
		searchParams.put("orderDire", "desc");
		Page<SelfConstruction> page = service.page(searchParams, new PageRequest(pageNumber - 1, pageSize, getSort("pubdate", "desc")));
		doWithPage(page, model);
		//model
		model.addAttribute("parentMenu", parentMenu());
		model.addAttribute("menu", english());
		model.addAttribute(english() + "s", page);
		model.addAttribute("sortType", sortType);
		model.addAttribute("sortTypes", sortTypes);
		model.addAttribute("sortDire", sortDire);
		/*将搜索条件编码成字符串，用于排序，分页的URL*/
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		//view
		return english() + "List";
	
	}
	
	@RequestMapping(value="/publish/{id}")
	public String publish(@PathVariable("id")Long id,
			RedirectAttributes map){
		return standardSubmit(id, map);
	}
	
	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable("id")Long id,RedirectAttributes redirectAttributes){
		return standardDelete(id, redirectAttributes);
	}
	
	@RequestMapping("/update/{id}")
	public String updateForm(@PathVariable("id")Long id,Model model){
		SelfConstruction sf = service.findOne(id);
		model.addAttribute("types", SelfConstruction.types);
		model.addAttribute("uploadUrl", propertiesHolder.getUploadUrl());
		model.addAttribute("fls", getFiles(sf));
		return standardUpdateForm(id, model);
	}
	
	private Map<String,String> getFiles(SelfConstruction sf) {
		// TODO Auto-generated method stub
		Map<String,String> fls = Maps.newConcurrentMap();
		String uuidname= sf.getAttachment();
		String filename= sf.getFilename();
		String[] uuids = uuidname.split(",");
		String[] files = filename.split(",");
		for (int i =0; i< uuids.length;i++){
			if(!StringUtils.isEmpty(uuids[i])){
				fls.put(uuids[i], files[i]);
			}
		}
		System.out.println("-------"+fls.size());
		return fls;
	}

	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String update(@ModelAttribute("_entity_") SelfConstruction e,@RequestParam("file")MultipartFile[] files ,HttpServletRequest request,RedirectAttributes redirectAttributes){
		if(files.length!=0 && !files[0].isEmpty() ){
			service.uploadAttach(request,files,e);
		}
		e.setStatus(SelfConstruction.REPAIR);
		e.setPubdate(new Date(System.currentTimeMillis()));
		return standardUpdate(e, redirectAttributes);
	}
	
	@RequestMapping("/create")
	public String createForm(Model model){
		model.addAttribute("types", SelfConstruction.types);
		return standardCreateForm(model);
	}
	
	@RequestMapping(value="/create",method=RequestMethod.POST)
	public String create(SelfConstruction e,@RequestParam("file")MultipartFile[] files ,HttpServletRequest request,RedirectAttributes redirectAttributes){
		if(files.length!=0 && !files[0].isEmpty()){
			service.uploadAttach(request,files,e);
		}
		e.setIsenabled(1);
		e.setPubdate(new Date(System.currentTimeMillis()));
		e.setUser(Holder.user.get().getId());
		e.setStatus(SelfConstruction.NORMAL);
		e.setTimes(1l);
		return standardCreate(e, redirectAttributes);
	}
	
	@RequestMapping("/view/{id}")
	public String view(@PathVariable("id")Long id, Model model){
		SelfConstruction sf = service.findOne(id);
		Long times = sf.getTimes();
		Long tm = times+1l;
		sf.setTimes(tm);
		service.update(sf);
		return standardView(id, model);
	}
	
	@RequestMapping(value = "import", method = RequestMethod.GET)
	public String importData(Model model){
		return standardImportData(model);
	}

	@RequestMapping(value = "doImport", method = RequestMethod.POST)
	public String doImport(@RequestParam("file") MultipartFile multipartFile,  RedirectAttributes redirectAttributes){
		return standardDoImport(multipartFile, redirectAttributes);
	}
	
	
	@ModelAttribute
	public void getEntity(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		standardGetEntity(id, model);
	}
	
	@RequestMapping(value = "/delAttac", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> byAccount(@RequestParam("uuid") String uuid,@RequestParam("id")Long id) {
		SelfConstruction sf = service.findOne(id);
		Map<String,String> fs = getFiles(sf);
		String uuids = sf.getAttachment();
		String files = sf.getFilename();
		
		String repairus = uuids.replace(uuid, "");
		String repairfnames = files.replace(fs.get(uuid), "");
		
		
		StringBuilder uuidrs= new StringBuilder();
		StringBuilder namers = new StringBuilder();
		
		String[] uuidnamelast = repairus.split(",");
		String[] fnamelast = repairfnames.split(",");
		
		Map<String,String> lasts= Maps.newConcurrentMap();
		for (int i=0;i<uuidnamelast.length;i++){
			if(!StringUtils.isEmpty(uuidnamelast[i])){
				uuidrs.append(uuidnamelast[i]+",");
				namers.append(fnamelast[i]+",");
				lasts.put(uuidnamelast[i], fnamelast[i]);
			}
		}
		

		sf.setAttachment(uuidrs.toString());
		sf.setFilename(namers.toString());
		
		service.update(sf);
		
		return lasts;
	}

}
